package com.xxmw.transaction.controller.brick;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.controller.BaseController;
import com.xxmw.transaction.model.brick.Brick;
import com.xxmw.transaction.model.subscribe.SymbolSub;
import com.xxmw.transaction.service.app.BourseApiService;
import com.xxmw.transaction.service.app.BrickService;
import com.xxmw.transaction.service.app.SymbolSubService;
import com.xxmw.transaction.valid.DecimalGt;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

/**
 * @author: yamoo
 * @Date: 2020-02-27 19:26
 **/
@RestController
@RequestMapping("/admin/brick")
public class BrickController extends BaseController{

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private BrickService brickService;

    @Autowired
    private SymbolSubService symbolSubService;

    @Autowired
    private BourseApiService bourseApiService;


    /**
     * 搬砖列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    @RequiresPermissions("brick:list")
    public R list (@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                   @RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize,
                   @RequestParam(value = "symbol", required = false) String symbol) {
        return R.ok(brickService.pageList(pageNum, pageSize, symbol));
    }

    /**
     * 搬砖新增
     * @param brick
     * @return
     */
    @PostMapping("save")
    @RequiresPermissions("brick:save")
    public R save (Brick brick) {

        //验证搬砖条件
        List<SymbolSub> subList = symbolSubService.getBySymbol(brick.getSymbol());

        if (null == subList || subList.size() < 2) {
            return R.error("至少两个交易所开启订阅该交易对才可搬砖");
        }

        brick.setStatus(Brick.Status.CLOSE.value());
        brickService.save(brick);
        return R.ok();
    }

    /**
     * 搬砖编辑
     * @param id
     * @param minProfitMargin
     * @param tradeNum
     * @return
     */
    @PostMapping("/update")
    @RequiresPermissions("brick:update")
    public R update (@RequestParam(value = "id") Integer id,
                     @NotBlank(message = "标题不能为空") @RequestParam(value = "title") String title,
                     @NotBlank(message = "描述不能为空") @RequestParam(value = "description") String description,
                     @DecimalGt(value = "0") @RequestParam(value = "minProfitMargin") String minProfitMargin,
                     @DecimalGt (value = "0") @RequestParam(value = "tradeNum") String tradeNum,
                     @RequestParam String rate) {
        Brick brick = brickService.getById(id);
        if (null == brick) {
            return R.error("记录不存在");
        }
        brick.setMinProfitMargin(new BigDecimal(minProfitMargin));
        brick.setTradeNum(new BigDecimal(tradeNum));
        brick.setTitle(title);
        brick.setDescription(description);
        brick.setRate(rate);

        brickService.updateById(brick);

        return R.ok();
    }

    /**
     * 搬砖开启关闭
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/enable")
    @RequiresPermissions("brick:enable")
    public R enable (@RequestParam(value = "id") Integer id, @RequestParam(value = "status") Integer status) {
        Brick brick = brickService.getById(id);
        if (null == brick) {
            return R.error("记录不存在");
        }
        if (brick.getStatus().equals(status)) {
            return R.error(Brick.Status.OPEN.value().equals(status) ? "该搬砖已开启" : "该搬砖已关闭");
        }
        brick.setStatus(status);
        brickService.updateById(brick);
        redisTemplate.delete("symbolList");
        return R.ok();
    }

    /**
     * 搬砖删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @RequiresPermissions("brick:delete")
    public R delete (@PathVariable Integer id) {
        QueryWrapper<Brick> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        brickService.remove(queryWrapper);
        return R.ok();
    }

    /**
     * 查询当前是否可以开启数据撮合
     * 至少有一个交易对已经开启搬砖且被至少两个交易所订阅 且当前线程池已关闭
     * true 可以开启 false不可开启
     * @return
     */
//    @GetMapping("/matchable")
//    public R matchable () {
//        boolean enable = false;
//        if (!brickService.isMatching()) {
//            Set<String> symbolList = brickService.symbolList();
//            if (!symbolList.isEmpty()) {
//                for (String s : symbolList) {
//                    List<SymbolSub> subList = symbolSubService.getBySymbol(s);
//                    if (null != subList && subList.size() >= 2) {
//                        enable = true;
//                        break;
//                    }
//                }
//            }
//        }
//        return R.ok(enable);
//    }

    /**
     * 撮合交易开关
     * @param status 0关闭 1开启
     * @return
     */
//    @GetMapping("/match/{status}")
//    public R match (@PathVariable Integer status) {
//        if (1 == status) {
//            if (brickService.isMatching()) {
//                return R.error("请勿重复开启");
//            }
//            Set<String> symbolList = brickService.symbolList();
//            if (symbolList.isEmpty()) {
//                return R.error("当前没有可用的搬砖的交易对");
//            }
//            for (String s : symbolList) {
//                List<SymbolSub> subList = symbolSubService.getBySymbol(s);
//                if (null != subList && subList.size() >= 2) {
//                    brickService.matchOpen();
//                    return R.ok();
//                }
//            }
//            return R.error("至少需要两个交易所订阅某个交易对才可进行数据撮合");
//        } else {
//            if (!brickService.isMatching()) {
//                return R.error("该任务已经关闭");
//            }
//            brickService.matchClose();
//            return R.ok();
//        }
//    }
}
